#  Copyright 2012 Eric Lawrey, Australian Institute of Marine Science
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

# Copies the 'overwrite' dataframe over the 'initial' dataframe
# If the overwrite has additional columns then these are added, if
# it has addition rows then these are added. Extra empty cells created
# are filled with NA.
# If initial is an empty data frame then the return value is the overwrite
# data frame.
# Example:
# overwrite <- data.frame(x=c(1,2,3),y=c("a","b","c"))
# initial <- data.frame(x=c(4,5),z="foo")
# overwriteDataframes(initial, overwrite)
#   x    z y
# 1 1  foo 1
# 2 2  foo 2
# 3 3 <NA> 3
#
# To replace the NA with a emply strings use:
# x <- overwriteDataframes(initial, overwrite)
# x[is.na(x)] <- ""
overwriteDataframes <- function(initial, overwrite) {
  # To merge the initial with the overwrite we must first make them
  # have matching rows and columns. The extra rows and columns will be filled with NA

  # If initial is blank then return overwrite.
  if ((nrow(initial) == 0) && (ncol(initial) == 0)) {
    return(overwrite)
  }

  # Find columns that are not specfied in the initial, create them and fill with NA
  extraColumns <- setdiff(union(names(initial),names(overwrite)),names(initial))
  initial[,extraColumns] <- NA
  
  # Find the extra rows and fill with NA
  initial[(nrow(initial)+1):nrow(overwrite),] <- NA
  
  initial[1:nrow(overwrite),names(overwrite)] <- overwrite
  return(initial)
}

